<template>
  <div class="content">
    <van-field v-model="telcode" placeholder="请输入验证码" >
      <template #button>
        <van-button @click="sendCode()" :disabled="codeflag" size="small" type="default">{{ text }}</van-button>
      </template>
    </van-field>
    <van-button @click="docheckcodeFn" :disabled="!flag" round block color="#ff6666" style="margin-top: 20px">下一步</van-button>
  </div>
</template>
<script>
import Vue from 'vue'
import { Field, Button, Toast } from 'vant'
import { dosendmsgcode, docheckcode } from '@/api/user'
Vue.use(Field)
Vue.use(Button)
Vue.use(Toast)
export default {
  data () {
    return {
      telcode: '',
      text: '发送验证码',
      timer: null,
      time: 5,
      codeflag: false
    }
  },
  computed: {
    flag () {
      return /\d{5}/.test(this.telcode)
    }
  },
  mounted () {
    this.sendCode()
  },
  methods: {
    sendCode () {
      dosendmsgcode({
        tel: localStorage.getItem('tel')
      }).then(res => {
        console.log(res.data)
      })
      this.timer = setInterval(() => {
        this.time--
        if (this.time <= 0) {
          this.text = '发送验证码'
          this.codeflag = false
          this.time = 5
          clearInterval(this.timer)
        } else {
          this.text = this.time + 's后重新发送'
          this.codeflag = true
        }
      }, 1000)
    },
    docheckcodeFn () {
      docheckcode({
        tel: localStorage.getItem('tel'),
        telcode: this.telcode
      }).then(res => {
        if (res.data.code === '10007') {
          Toast('验证码错误')
        } else {
          this.$router.push('/register/step3')
        }
      })
    }
  }
}
</script>
